<?php

/**
 * Albireo Kernel
 *
 * @copyright  Copyright (c) 2010 Albireo Solutions
 * @package    Kernel
 */

namespace WebModule;

use Nette\Application\Presenter;
use Nette\Environment;
use GettextExtractor\Translator;

/**
 * Base class for all application presenters.
 *
 * @author     Albireo Solutions
 * @package    Kernel
 */
abstract class BasePresenter extends Presenter{

    /**
     * language code
     * @var string
     * @persistent
     */
    public $lang;

    /**
     * Sets the application to the new directory structure. IMPORTANT!
     * @var boolean
     */
    public $oldModuleMode = FALSE;

    /**
     * Sets the layout mode to the new one. Desktop is loading properly
     * (into the @layout.phtml) when it's turned on only with the statement
     * {include ../@layout.phtml} in the template.
     *
     * @var boolean
     */
    public $oldLayoutMode = FALSE;

    public function startup() {
        parent::startup();
	date_default_timezone_set('Europe/Prague'); // TODO: use time zone recognition
	$this->setLocalization();
    }

    private function setLocalization() {
        if ( $this->lang===NULL || !array_key_exists($this->lang,Translator::$supported_languages) ) {
            $this->lang = NULL;
            // find prefered language
            if(($list = strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']))){
                if(preg_match_all('/([a-z]{1,8}(?:-[a-z]{1,8})?)(?:;q=([0-9.]+))?/', $list, $list)){
                    $langlist = array_combine($list[1], $list[2]);
                    foreach($langlist as $n => $v) {
                        $langlist[$n] = +$v ? +$v : 1;
                    }
                    arsort($langlist);
                    //var_dump($langlist);
                    while(key($langlist) && $this->lang===NULL){
                        $lang=key($langlist);
                        //echo " key ".$lang;
                        if(array_key_exists($lang,Translator::$supported_languages)){
                            $this->lang=$lang;
                        }
                        next($langlist);
                    }
                }
            }
            $this->lang=($this->lang===NULL)?"en":$this->lang; // u.s. english is default
        }

	// set language and gettext
	Environment::setVariable('lang', $this->lang);
        $this->template->lang = $this->lang;
	$translator = new Translator(
		Environment::getVariable('lang'), realpath(APP_DIR . '/locale'));
	$this->template->setTranslator($translator);
    }
}
